const mysql = require('mysql')

/**
 *  数据库单链接

// 1，创建连接
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'jianpan',
  database: 'yygl',
  useConnectionPooling: true,
})

// 2，连接
connection.connect((err) => {
  if (err) {
    console.log('mysql-serve err')
    console.log(err);
  } else {
    console.log('mysql-serve...ok')
  }
})

function sqlQuery(strSql, arr) {
  return new Promise((resolve, reject) => {
    connection.query(strSql, arr, (err, results) => {
      if (err) {
        reject(err)
        // connection.end();
      } else {
        resolve(results)
      }
    })
  })
}

// connection.end(function(err){
//   console.log(err);
// })
 */

/**
 * 数据库 连接池
 */
const pool = mysql.createPool({
  host: 'localhost',
  user: 'root',
  password: 'jianpan',
  database: 'yygl',
})

// 测试是否连接成功
pool.getConnection(function (err, connection) {
  if (err) {
    console.log('mysql-sever...error')
    console.log(err)
  } else {
    console.log('mysql-sever...ok')
  }

  connection.release()
})

function sqlQuery(sql, arr) {
  return new Promise((resolve, reject) => {
    pool.getConnection(function (err, connection) {
      // console.log(err)
      if (err) {
        reject(err)
      } else {
        connection.query(sql, arr, function (qerr, results) {
          //释放连接
          connection.release()

          //promise 判断
          if (qerr) {
            reject(qerr)
          } else {
            resolve(results)
          }
        })
      }
    })
  })
}

module.exports = sqlQuery
